import 'dart:developer';

import 'package:erp/Entity/ServerResponse.dart';
import 'package:erp/Entity/SignInResult.dart';
import 'package:erp/EventBus/EventBus.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/ProgressDialog.dart';
import 'package:erp/UI/Pages/MainPage.dart';
import 'package:erp/UI/Pages/SettingsPages/ServerSettingsPage.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';
import '../CodeResources/Colors.dart';
import '../CodeResources/Localization.dart';
import '../Routes.dart';
import "../Components/PageFrame.dart";



class SignInPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SignInState();
}

class SignInState extends State<SignInPage> {
  var avatarImage = "assets/pictures/boy.png";
  var signInButtonState = "كىرىڭ";
  ProgressDialog proggressDialog;
  var _userNameController = TextEditingController(text: globalPreferences.getString("userName"));
  var _userPasswordController = TextEditingController();

  var ids = <int>[];

  @override
  void initState() {
    proggressDialog = ProgressDialog(context: context);
    ids = [
      globalBus.subscribe(Events.FIRSTDATA_SELECT_SUCCESS, (bus, _) {setState(() {
        proggressDialog.close();
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => MainPage()));
      });}),

      globalBus.subscribe(Events.ACCOUNT_SIGNIN_ERROR, (bus, error) {setState(() {
        setState(() {
          proggressDialog.close();
          showMessageDialog(context, title: "كىرىش مەغلۇپ بولدى!", content: error.toString());
        });
      });}),

      globalBus.subscribe<MapEntry<String, String>>(Events.ACCOUNT_SIGNIN_REQUEST, (bus, data) {setState(() {
        proggressDialog.show();
      });}),
    ];

    super.initState();
  }

  @override
  void dispose() {
    globalBus.unSubscribeAllByIds(ids);
    super.dispose();
  }

  var index = 0;

  @override
  Widget build(BuildContext context) {

    var currentLocale = AppLocalizations.of(context);

    return Directionality(
        textDirection: currentLocale.textDirection,
        child: PageFrame(
          borderColor: Theme.of(context).primaryColor,
          child: Scaffold(
            appBar: AppBar(
              title: Text(currentLocale.signInTitle,
                style: TextStyle(
                    fontFamily: currentLocale.fontFamilyOfTitle
                ),
              ),
              centerTitle: true,
              actions: <Widget>[
                IconButton(icon: Icon(Icons.language), onPressed: (){
                  setState(() {

                  });
                }),
                IconButton(icon: Icon(Icons.settings), onPressed: () async {
                  await Navigator.of(context).push(MaterialPageRoute(builder: (context) => ServerSettingsPage()));
                })
              ],
            ),

            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Align(
                  child: CircleAvatar(
                    backgroundImage: AssetImage(avatarImage),
                    radius: 64.0,
                    backgroundColor: Colors.orange,
                  ),
                ),
                SizedBox(height: 10.0,),
                Align(
                  child: AnimatedContainer(
                    duration: Duration(seconds: 1),
                    width: 300.0,
                    child: Column(
                      children: <Widget>[
                        TextField(
                          decoration: InputDecoration(
                            icon: Icon(Icons.person),
                            hintText: currentLocale.accountNameHint,
                            labelText: currentLocale.accountName,
                          ),
                          controller: _userNameController,
                        ),
                        SizedBox(height: 10.0,),
                        TextField(
                          decoration: InputDecoration(
                              icon: Icon(Icons.lock),
                              hintText: currentLocale.accountPasswordHint,
                              labelText: currentLocale.accountPassword
                          ),
                          obscureText: true,
                          controller: _userPasswordController,
                        )
                      ],
                    ),
                  ),
                ),
                SizedBox(height: 20.0,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    GestureDetector(
                      child: Container(
                        width: 150.0,
                        child: Text(
                          currentLocale.signIn,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.white
                          ),
                        ),
                        padding: EdgeInsets.all(12.0),
                        decoration: BoxDecoration(
                            color: themeColor,
                            borderRadius: BorderRadius.circular(8.0)
                        ),
                      ),
                      onTap: () {
//                        Navigator.pushReplacementNamed(context, PagesRouter.mainPage);
                        globalBus.publish(Events.ACCOUNT_SIGNIN_REQUEST, MapEntry(_userNameController.text, _userPasswordController.text));
                      },
                    ),
                  ],
                ),
                SizedBox(height: 10.0,),
                Align(
                  child: Text(currentLocale.or,
                      style: TextStyle(
                          color: themeColor,
                          fontStyle: FontStyle.italic
                      )
                  ),
                ),

                SizedBox(height: 10.0,),
                Align(child: Text(currentLocale.createYourNewAccount,
                  style: TextStyle(
                    color: themeColor,
                    decoration: TextDecoration.underline,
                  ),
                ))
              ],
            ),


            bottomNavigationBar:
            Container(
              height: 60.0,
              color: themeColor,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("2018 تۇغلۇق تور-تېخنىكا چەكلىك مەسئۇلىيەت شىركىتى",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.white,
                        fontFamily: currentLocale.fontFamilyOfTitle
                    ),
                  ),
                ],
              ),
            ),
          ),
        )
    );
  }
}


